<!-- register_captcha -->
<template>
  <div class="app_contain">
    <div class="contain">
      <header></header>
      <div class="center">
        <div class="login_card">
          <img src="@/assets/img/logo.svg" alt="logo" />
          <el-steps :active="1" finish-status="success" align-center>
            <el-step title="填写信息"></el-step>
            <el-step title="安全验证"></el-step>
          </el-steps>
          <el-input placeholder="请输入验证码" v-model="captcha" size="large">
            <template slot="prepend">验证码</template>
          </el-input>
          <div>
            <el-button
              type="primary"
              plain
              size="medium"
              @click="send_captcha"
              :disabled="isDisabled"
              >{{ buttonName }}</el-button
            >
          </div>
          <div class="login_btn_contain" @click="submit">提交</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "register_captcha",
  data() {
    return {
      CountDown: 60,
      buttonName: "发送验证码",
      isDisabled: false,
      captcha: "",
      check_account_phone:
        /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
      isPhone: false,
      captcha_id: "",
    };
  },
  created() {
    if (sessionStorage.getItem("CountDownInfo")) {
      this.CountDown = JSON.parse(
        sessionStorage.getItem("CountDownInfo")
      ).CountDown;
      this.isDisabled = JSON.parse(
        sessionStorage.getItem("CountDownInfo")
      ).isDisabled;
      this.captcha_id = JSON.parse(
        sessionStorage.getItem("CountDownInfo")
      ).captcha_id;
      this.$store.state.login.captcha_id = this.captcha_id;
    }
    if (this.isDisabled) {
      let timerId = setInterval(() => {
        this.CountDown--;
        this.buttonName = this.CountDown + "秒后重试";
        if (this.CountDown <= 0) {
          clearInterval(timerId);
          this.buttonName = "重新发送";
          this.CountDown = 60;
          this.isDisabled = false;
        }
      }, 1000);
    }
    let isPhone = JSON.parse(sessionStorage.getItem("CountDownInfo")).isPhone;
    if (isPhone) {
      this.isPhone = isPhone;
    }
    
    window.addEventListener("beforeunload", () => {
      sessionStorage.setItem(
        "CountDownInfo",
        JSON.stringify({
          CountDown: this.CountDown,
          isDisabled: this.isDisabled,
          isPhone: this.isPhone,
          captcha_id: this.$store.state.login.captcha_id,
        })
      );
    });
  },
  beforeRouteLeave(to, from, next) {
    /*
      to:router 即将要进入的路由对象
      from:router  当前导航正要离开的路由
      next()进行管道中的下一个钩子
      最后要确保调用next方法，否则钩子不会被resolved
    */
    if (to.name !== "login") {
      sessionStorage.setItem(
        "CountDownInfo",
        JSON.stringify({
          CountDown: this.CountDown,
          isDisabled: this.isDisabled,
          isPhone: this.isPhone,
          captcha_id: this.$store.state.login.captcha_id,
        })
      );
    }
    next();
  },
  methods: {
    // abc(){
    //   console.log('222')
    // },
    send_captcha() {
      const { account, password, username } = JSON.parse(
        sessionStorage.getItem("userinfo")
      );
      if (account && password && username) {
        this.isDisabled = true;
        let timerId = setInterval(() => {
          this.CountDown--;
          this.buttonName = this.CountDown + "秒后重试";
          if (this.CountDown <= 0) {
            clearInterval(timerId);
            this.buttonName = "重新发送";
            this.CountDown = 60;
            this.isDisabled = false;
          }
        }, 1000);
        if (this.check_account_phone.test(account)) {
          this.$store
            .dispatch("login/sms", account)
            .then((data) => {
              this.$message.success(data);
            })
            .catch((error) => {
              // this.$message.error("验证码发送失败，请重试");
              clearInterval(timerId);
              this.buttonName = "重新发送"; 
              this.CountDown = 60;
              this.isDisabled = false;
            });
          this.isPhone = true;
        } else {
          this.$store
            .dispatch("login/email", account)
            .then((data) => {
              this.$message.success(data);
            })
            .catch((error) => {
              // this.$message.error("验证码发送失败，请重试");
              clearInterval(timerId);
              this.buttonName = "重新发送";
              this.CountDown = 60;
              this.isDisabled = false;
            });
        }
      } else {
        this.$message.warning("请返回上一步完善信息");
      }
    },
    submit() {
      if (!this.captcha) {
        this.$message.warning("请输入验证码");
      } else {
        let userinfo = JSON.parse(sessionStorage.getItem("userinfo"));
        userinfo.captcha = this.captcha;
        userinfo.captcha_id = this.$store.state.login.captcha_id;
        if (this.isPhone) {
          this.$store
            .dispatch("login/registerUserByPhone", userinfo)
            .then((data) => {
              this.$notify.success({
                title: "注册成功",
                message: "您的账号为 " + data.data.phone_number,
                showClose: false,
              });
              sessionStorage.removeItem("userinfo");
              sessionStorage.removeItem("CountDownInfo");
              this.$store.state.login = {};
              this.$router.push("/login");
            });
        } else {
          this.$store
            .dispatch("login/registerUserByEmail", userinfo)
            .then((data) => {
              this.$notify.success({
                title: "注册成功",
                message: "您的账号为 " + data.data.email,
                showClose: false,
              });
              sessionStorage.removeItem("userinfo");
              sessionStorage.removeItem("CountDownInfo");
              this.$store.state.login = {};
              this.$router.push("/login");
            });
        }
      }
    },
  },
  mounted: function () {},
};
</script>

<style lang='scss' scoped>
@import "@/assets/css/login.scss";
</style>